package com.yunlong.softpark.controller;

import com.yunlong.softpark.common.enums.BaseErrorCodeEnum;
import com.yunlong.softpark.core.exception.SysException;
import com.yunlong.softpark.core.support.web.controller.BaseController;
import com.yunlong.softpark.core.wrapper.ResultWrapper;
import com.yunlong.softpark.dto.CommentCheckDto;
import com.yunlong.softpark.dto.MessageSuccessDto;
import com.yunlong.softpark.dto.UserInfo;
import com.yunlong.softpark.form.CommentForm;
import com.yunlong.softpark.form.CommentGetForm;
import com.yunlong.softpark.redis.RedisRepository;
import com.yunlong.softpark.service.CommentService;
import com.yunlong.softpark.service.RecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.ParseException;
import java.util.List;

/**
 * @author Cui
 * @email ${email}
 * @date 2020-07-21 16:54:16
 */
@Api(value = "CommentController", tags = {"评论接口"})
@RestController
@Slf4j
@RequestMapping("/comment")
public class CommentController extends BaseController<UserInfo> {

    @Autowired
    CommentService commentService;

    @Autowired
    RedisRepository redisRepository;

    @Autowired
    RecordService recordService;

    /**
     * 不需要token
     * 接收前端传递的colomn_id，并根据colomn_id查询所有该栏目下的评论
     * 返回含（content，time，user_id）的list集合
     *
     * @param commentGetForm
     * @return
     */
    @ApiOperation("查询栏目下的所有评论")
    @RequestMapping(path = "/check", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultWrapper getCommentData(@Valid @RequestBody CommentGetForm commentGetForm, BindingResult bindingResult) throws ParseException {
        try {
            validateParams(bindingResult);
            List<CommentCheckDto> list = commentService.getCommentData(commentGetForm.getColumnId());
            return ResultWrapper.successWithData(list);
        } catch (Exception e) {
            log.info("CommentController.getCommentData");
            return ResultWrapper.failure(e.getMessage());
        }


    }

    /**
     * 需要token
     * 接收前端传递的评论信息（userId,content，colomnId）
     * 向数据库中添加一条新的评论
     * 成功则返回Succes
     *
     * @param commentForm
     * @return
     */
    @ApiOperation("添加评论")
    @RequestMapping(path = "/insert", method = RequestMethod.POST)
    public ResultWrapper insertCommentData(@Valid @RequestBody CommentForm commentForm,
                                           BindingResult bindingResult,
                                           @RequestHeader("ANSWER_ACCESS_TOKEN") String token,
                                           HttpServletRequest request) {
        try {
            validateParams(bindingResult);
            if(token != null){
                String userId = redisRepository.selectAccessToken(token);
                String commentId = commentService.insertCommentData(commentForm, userId);
                recordService.saveRecord(request.getRemoteAddr(),3,commentId,userId);
            }else {
                String commentId = commentService.insertCommentData(commentForm, null);
                recordService.saveRecord(request.getRemoteAddr(),3,commentId,null);
            }
            return ResultWrapper.success();
        } catch (DataIntegrityViolationException e){
            log.info("record表违反唯一约束，但是插入成功");
            return ResultWrapper.success();
        }  catch (Exception e) {
            log.info("CommentController.insertCommentData");
            return ResultWrapper.failure(e.getMessage());
        }
    }

}
